import re
from lxml import etree
import requests

headers = {
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
}

response = requests.get(
    'https://wallhaven.cc/search?categories=010&purity=110&atleast=1920x1080&ratios=landscape&sorting=random&order=desc',
    headers=headers)
response.encoding = 'utf-8'
etree_ = etree.HTML(response.text)
imgs = etree_.xpath('//section[@class="thumb-listing-page"]/ul/li')
for i in imgs:
    try:
        img = i.xpath('.//img[@class="lazyload"]/@data-src')[0]
        img_two = img.split("/")[-1]
        img_type = img_two.split(".")[-1]
        img_name = img_two.split(".")[0]
        img_url = f'https://w.wallhaven.cc/full/{img_name[:2]}/wallhaven-{img_name}.{img_type}'
        print(img_url)
        response = requests.get(img_url, headers=headers)
        name = f'./{img_name}.{img_type}'
        with open(name, 'wb') as Open:
            Open.write(response.content)
    except Exception as e:
        print(e)